package com.drinks.yiniang.common.help;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.drinks.yiniang.R;
import com.drinks.yiniang.entity.pay.PayResult;
import com.drinks.yiniang.entity.pay.WeiXinPayJson;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * Created by han on 2018/10/30 0030.
 */

public class PayManager {
    public static final int PAY_CHANNEL_WX = 0x01;//微信支付
    public static final int PAY_CHANNEL_ALIPAY = 0x02;//支付宝支付
    public static final int PAY_CHANNEL_WALLET = 0x05;//钱包支付

    private static final int MSG_PAY_ALI = 0x0A;

    public static final String PAY_TYPE_BUY_GOODS_PAY = "1";//购买商品支付
    public static final String PAY_TYPE_RECHARGE_PAY = "2";//充值支付
    public static final String PAY_TYPE_ORDER_LIST_PAY = "3";//订单列表支付
    public static final String PAY_TYPE_ORDER_DETAIL_PAY = "4";//订单详情支付

    private PayResultListener payResultListener;

    private IWXAPI api;

    private Activity mActivity;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_PAY_ALI: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getMemo();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        ToastUtils.showShort(R.string.text_pay_success);
                        if(payResultListener != null) {
                            payResultListener.onPaySuccess(mActivity.getString(R.string.text_pay_success));
                        }
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        ToastUtils.showShort(resultInfo);
                        if(payResultListener != null) {
                            payResultListener.onPayFail(resultStatus,resultInfo);
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    public PayManager(Activity activity) {
        this.mActivity = activity;
    }

    public void slingAiPay(final String aliPayString) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(mActivity);
                Map<String, String> result = alipay.payV2(aliPayString, true);

                Message msg = new Message();
                msg.what = MSG_PAY_ALI;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    public void slingWXPay(WeiXinPayJson.WeiXinPayData wxPay, String pageType) {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(mActivity, Constants.WX_APPID);
        }

        if(pageType == null) {
            pageType = "app";
        }

        PayReq req = new PayReq();

        req.appId = wxPay.getAppid();
        req.partnerId = wxPay.getPartnerid();
        req.prepayId = wxPay.getPrepayid();
        req.nonceStr = wxPay.getNoncestr();
        req.timeStamp = wxPay.getTimestamp();
        req.packageValue = wxPay.getPackages();
        req.sign = wxPay.getSign();
        req.extData = pageType;//optional 参数

        ToastUtils.showShort(mActivity.getString(R.string.text_load_wx_pay));

        api.registerApp(Constants.WX_APPID);

        api.sendReq(req);
    }

    public void setPayResultListener(PayResultListener payResultListener) {
        this.payResultListener = payResultListener;
    }

    public void destroyPayRegister() {
        if (api != null) {
            api.unregisterApp();
        }

        mHandler.removeCallbacksAndMessages(null);
        mHandler = null;
        mActivity = null;

        setPayResultListener(null);
    }

    public interface PayResultListener {
        void onPaySuccess(String msg);
        void onPayFail(String errCode, String errMsg);
    }
}
